package me.monster.smarttraffic.ui.bus;

import java.util.Map;
import java.util.Random;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import me.monster.smarttraffic.base.BasePresenter;
import me.monster.smarttraffic.net.RemoteService;

/**
 * @description
 * @author: Created jiangjiwei in 2020-02-13 15:45
 */
public class BusPresenter extends BasePresenter<BusContract.View> implements BusContract.Presenter {
    public static final int ERROR_STATION_DISTANCE = 100;
    public static final int ERROR_STATION_ENV = 200;
    private static final String TAG = "BusPresenter";

    @Override
    public void fetchDistance(int stationPosition) {
        Disposable stationDistanceDis = RemoteService.getInstance().busDistanceByStation(stationPosition)
                .subscribe(new Consumer<Map<String, Integer>>() {
                    @Override
                    public void accept(Map<String, Integer> map) throws Exception {
                        map.put("bus_1", new Random().nextInt(1000));
                        map.put("bus_2", new Random().nextInt(1000));
                        Integer bus1 = map.get("bus_1");
                        Integer bus2 = map.get("bus_2");
                        iView.showDistance(bus1 == null ? 0 : bus1, bus2 == null ? 0 : bus2);
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        handleError(throwable);
                        iView.showError(ERROR_STATION_DISTANCE);
                    }
                });
        addDispose(stationDistanceDis);
    }

    @Override
    public void fetchEnv(int stationPosition) {
        Disposable stationDis = RemoteService.getInstance().busEnvByStation(stationPosition)
                .subscribe(new Consumer<Map<String, String>>() {
                    @Override
                    public void accept(Map<String, String> map) throws Exception {
                        for (String s : map.keySet()) {
                            map.put(s, String.valueOf(new Random().nextInt(50)));
                        }
                        iView.showEnv(map.get("pm"), map.get("temperature"), map.get("humidity"), map.get("co"));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        handleError(throwable);
                        iView.showError(ERROR_STATION_ENV);
                    }
                });
        addDispose(stationDis);
    }
}
